import sheinShopConfig from "./platform/shein/sheinShopConfig";
import sheinSemiPlatformConfig from "./platform/shein/sheinSemiPlatformConfig";
import sheinSelfPlatformConfig from "./platform/shein/sheinSelfPlatformConfig";
import type { TStartData, TManualVerifyGoods, TimingConfig } from "./type";

let skuInfoMap = {};

function clearData() {}

let getRequestHeaders = () => {
  return {
    "Content-Type": "application/json",
  };
};
let startAutoAddGoods: ({
  action,
  data,
}: {
  action: string;
  data: any;
}) => Promise<void> = () => {
  alert("该平台暂未实现");
  return Promise.resolve();
};

let manualVerifyPageGoods: (
  config: TManualVerifyGoods
) => Promise<{ action: string }> = async ({}) => {
  return new Promise((resolve) => {
    alert("该平台暂未实现");
    resolve({ action: "end" });
  });
};

let startQuickMode: ({
  action,
  data,
}: {
  action: string;
  data: any;
}) => void = () => {
  alert("该平台暂未实现");
};

function setConfigByPlatform(platform: string, activeType: string) {
  if (platform === "shein") {
    if (activeType === "shop") {
      ({ manualVerifyPageGoods } = sheinShopConfig);
    } else if (activeType === "semiPlatform") {
      ({ manualVerifyPageGoods, startQuickMode } = sheinSemiPlatformConfig);
    } else if (activeType === "selfPlatform") {
      ({ manualVerifyPageGoods, startAutoAddGoods, startQuickMode } = sheinSelfPlatformConfig);
    }
  }
}

// 在全局添加时间控制配置

const timing: TimingConfig = {
  baseDelay: 500, // 3秒基础延迟
  randomRange: 500, // 0-7秒随机延迟
  fatigueThreshold: 10, // 连续10次操作后触发疲劳模式
};

// Loading 遮罩管理器
const baoyiCustomPlugLoadingManager = {
  // 初始化遮罩元素
  init: function () {
    // 如果已经存在则不再创建
    if (document.getElementById("js-loading-overlay")) return;

    // 创建遮罩元素
    const overlay = document.createElement("div");
    overlay.id = "js-loading-overlay";

    // 创建内容容器
    const content = document.createElement("div");
    content.className = "js-loading-content";

    // 创建 spinner
    const spinner = document.createElement("div");
    spinner.className = "js-loading-spinner";

    // 创建文本元素
    const text = document.createElement("div");
    text.id = "js-loading-text";
    text.className = "js-loading-text";
    text.textContent = "加载中...";

    // 组装结构
    content.appendChild(spinner);
    content.appendChild(text);
    overlay.appendChild(content);
    document.body.appendChild(overlay);

    // 添加样式
    this.addStyles();
  },

  // 添加样式
  addStyles: function () {
    const style = document.createElement("style");
    style.textContent = `
      #js-loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        display: none;
        justify-content: center;
        align-items: center;
        z-index: 9999;
      }
      
      .js-loading-content {
        background-color: white;
        padding: 20px;
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        align-items: center;
        min-width: 200px;
      }
      
      .js-loading-spinner {
        border: 4px solid rgba(0, 0, 0, 0.1);
        border-radius: 50%;
        border-top: 4px solid #3498db;
        width: 40px;
        height: 40px;
        animation: js-loading-spin 1s linear infinite;
        margin-bottom: 15px;
      }
      
      .js-loading-text {
        margin-top: 10px;
        font-size: 16px;
        color: #333;
      }
      
      @keyframes js-loading-spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
    `;
    document.head.appendChild(style);
  },

  // 显示 loading
  show: function (text = "加载中...") {
    this.init(); // 确保元素已初始化
    const overlay = document.getElementById("js-loading-overlay");
    const loadingText = document.getElementById("js-loading-text");
    if (loadingText) {
      loadingText.textContent = text;
    }
    if (overlay) {
      overlay.style.display = "flex";
    }
  },

  // 隐藏 loading
  hide: function () {
    const overlay = document.getElementById("js-loading-overlay");
    if (overlay) {
      overlay.style.display = "none";
    }
  },

  // 设置提示文字
  setText: function (text: string) {
    const loadingText = document.getElementById("js-loading-text");
    if (loadingText) {
      loadingText.textContent = text;
    }
  },
};

// 将 LoadingManager 注册到 window 对象上，供其他文件使用
(window as any).baoyiCustomPlugLoadingManager = baoyiCustomPlugLoadingManager;

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === "startAutoRegistration") {
    checkLoginAndStartScraping(request);
  }
});

// 智能延迟函数
function intelligentDelay(pageCount: number): Promise<void> {
  return new Promise((resolve) => {
    // 疲劳模式检测
    const fatigueMultiplier = pageCount > timing.fatigueThreshold ? 1.5 : 1;
    // 计算最终延迟时间
    const delay =
      timing.baseDelay * fatigueMultiplier + Math.random() * timing.randomRange;

    setTimeout(resolve, delay);
  });
}

// 开始后禁用按钮
function startAutoMaticallyAgreeToNegotiateChangeBtn(actionType: string) {
  baoyiCustomPlugLoadingManager.show("正在操作中，请稍候...");
}

function endAutoMaticallyAgreeToNegotiateChangeBtn(actionType: string) {
  baoyiCustomPlugLoadingManager.hide();
}

// 检查token是否过期（针对时间戳格式）
function checkTokenExpired(expiresIn: string | number): boolean {
  if (!expiresIn) return true;

  // 统一转换为数字
  const expiryTime =
    typeof expiresIn === "string" ? parseInt(expiresIn) : expiresIn;

  // 获取当前时间戳（毫秒）
  const currentTime = new Date().getTime();
  return currentTime > expiryTime;
}

async function startManualVerifyPageGoods({
  multiplierMinInput,
  multiplierMaxInput,
  action,
  skuInfoMap,
  platform,
  shopId,
  activeType,
}: TManualVerifyGoods) {
  try {
    const result = await manualVerifyPageGoods({
      multiplierMinInput,
      multiplierMaxInput,
      action,
      skuInfoMap,
      platform,
      shopId,
      activeType,
    });
    if (result?.action === "next") {
      startManualVerifyPageGoods({
        multiplierMinInput,
        multiplierMaxInput,
        action,
        skuInfoMap,
        platform,
        shopId,
        activeType,
      });
    } else {
      endAutoMaticallyAgreeToNegotiateChangeBtn(action);
    }
  } catch (error) {
    endAutoMaticallyAgreeToNegotiateChangeBtn(action);
    alert(error);
  }
}

async function checkLoginAndStartScraping({
  action,
  data,
}: {
  action: string;
  data: TStartData;
}) {
  const storage = await chrome.storage.sync.get([
    "baoyiplus_accessToken",
    "baoyiplus_expiresIn",
  ]);
  const { platform, activeType, autoAddGoods, isOnlyAddGoods, pluginMode } =
    data;
  const { baoyiplus_accessToken = "", baoyiplus_expiresIn = 0 } = storage;

  if (baoyiplus_accessToken) {
    const isExpired = checkTokenExpired(baoyiplus_expiresIn);
    if (!isExpired) {
      clearData();
      setConfigByPlatform(platform, activeType);
      if (pluginMode === "visualizationMode") {
        if (autoAddGoods || isOnlyAddGoods) {
          startAutoAddGoods({
            action,
            data: {
              ...data,
              baoyiplus_accessToken,
            },
          });
        } else {
          startAutoMaticallyAgreeToNegotiateChangeBtn(action);
          startManualVerifyPageGoods({
            action,
            skuInfoMap,
            ...data,
          });
        }
      } else if (pluginMode === "quickMode") {
        startQuickMode({
          action,
          data,
        });
      }
    } else {
      alert("登录已经过期，请先点击右上角重新登录");
    }
  } else {
    alert("还未登录，请先点击右上角插件进行登录");
  }
}
